package com.ym521.emojipack.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.DynamicDrawableSpan;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

import com.ym521.emojipack.EmojiPackHelper;
import com.ym521.emojipack.R;
import com.ym521.emojipack.emoji.EmojiPackHandler;


/**
 * @author Ym
 */
public final class EmojiPackTextView extends AppCompatTextView {
    private int mEmojiconSize;
    private int mEmojiconAlignment;
    private int mEmojiconTextSize;
    private int mTextStart = 0;
    private int mTextLength = -1;
    private boolean mUseSystemDefault = false;

    public EmojiPackTextView(Context context) {
        super(context);
        init(null);
    }

    public EmojiPackTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public EmojiPackTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        float textSize = getTextSize();
        //默认放大 20%
        float packSize = textSize * EmojiPackHelper.Builder.EMOJI_ENLARGE;
        mEmojiconSize = (int) packSize;
        mEmojiconTextSize = (int) textSize;
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.EmojiPackTextView);
            mEmojiconAlignment = a.getInt(R.styleable.EmojiPackTextView_emojiPackAlignment, DynamicDrawableSpan.ALIGN_CENTER);
            mTextStart = a.getInteger(R.styleable.EmojiPackTextView_emojiPackTextStart, 0);
            mTextLength = a.getInteger(R.styleable.EmojiPackTextView_emojiPackTextLength, -1);
            mUseSystemDefault = a.getBoolean(R.styleable.EmojiPackTextView_emojiPackUseSystemDefault, false);
            a.recycle();
        }
        setText(getText());
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (!TextUtils.isEmpty(text)) {
            SpannableStringBuilder builder = new SpannableStringBuilder(text);
            EmojiPackHandler.addEmojis(getContext(), builder, mEmojiconSize, mEmojiconAlignment, mEmojiconTextSize, mTextStart, mTextLength, mUseSystemDefault);
            text = builder;
        }
        super.setText(text, type);
    }

    /**
     * 设置表情符号的大小（以像素为单位）。
     */
    public void setEmojiconSize(int pixels) {
        mEmojiconSize = pixels;
        super.setText(getText());
    }

    /**
     * 设置是否使用系统默认表情符号
     */
    public void setUseSystemDefault(boolean useSystemDefault) {
        mUseSystemDefault = useSystemDefault;
    }
}
